import 'dart:typed_data';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

// ignore: must_be_immutable
class ImgDetailPage extends StatelessWidget {
  final List<BrnBasicGroupConfig> allConfig;

  /// 初始位于第几组，默认 0
  final int initGroupId;

  /// 初始位于组内的第几个，默认 0
  final int initIndexId;
  BrnGalleryDetailConfig? themeData;
  ImgDetailPage({
    super.key,
    required this.allConfig,
    this.initGroupId = 0,
    this.initIndexId = 0,
    this.themeData,
  });
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          left: 0,
          top: 0,
          right: 0,
          bottom: 0,
          child: BrnGalleryDetailPage(
            allConfig: allConfig,
            initGroupId: initGroupId,
            initIndexId: initIndexId,
            themeData: themeData,
          ),
        ),
        Positioned(
          right: 20,
          bottom: 20,
          child: GestureDetector(
            onTap: _downloadBtnClicked,
            child: const SizedBox(
              width: 44,
              height: 44,
              child: Icon(
                Icons.file_download_outlined,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _downloadBtnClicked() async {
    var p = await Permission.storage.status;
    if (p.isDenied) {
      Permission.storage.request();
    } else {
      EasyLoading.show();
      BrnBasicGroupConfig config = allConfig[initGroupId];
      BrnBasicItemConfig itemConfig = config.configList![initIndexId];
      String img = '';
      if (itemConfig is BrnPhotoItemConfig) {
        img = itemConfig.url;
        if (img.isNotEmpty) {
          var response = await Dio().get(
            img,
            options: Options(
              responseType: ResponseType.bytes,
            ),
          );
          final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data),
          );
          if (result == null || result == '') {
            EasyLoading.showToast("保存失败");
          } else {
            EasyLoading.showToast("保存成功");
          }
        }
      }
      EasyLoading.dismiss();
    }
  }
}
